import { Button, Modal, Progress, Select } from "antd"
import * as pdfjsLib from "pdfjs-dist"
import type { TextItem } from "pdfjs-dist/types/src/display/api"
import React, { useEffect, useState } from "react"

import { _callApi, getUserShopList } from "~utils/tools"

pdfjsLib.GlobalWorkerOptions.workerSrc =
  "https://cdnjs.cloudflare.com/ajax/libs/pdf.js/3.4.120/pdf.worker.min.js"

// 定义接口
interface DyBicCrawerModalProps {
  showBicModal: boolean
  handleClose: () => void
}

// BIC数据抓取逻辑
const fetchBicData = async () => {
  const bicUrl =
    "https://fxg.jinritemai.com/byteshop/bic/getOrderCodePdf?size=100&template=bic_50_30"
  try {
    const response = await fetch(bicUrl, {
      method: "GET"
    })
    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`)
    }
    const arrayBuffer = await response.arrayBuffer()
    // 加载 PDF 文档
    const pdf = await pdfjsLib.getDocument(arrayBuffer).promise
    const bicCodes = [] // 初始化空数组来存储BIC数据

    // 逐页提取文本
    for (let i = 1; i <= pdf.numPages; i++) {
      const page = await pdf.getPage(i)
      const textContent = await page.getTextContent()
      const text = textContent.items
        .map((item) => (item as TextItem).str)
        .join(" ")
        .trim()
      bicCodes.push(text) // 将每页的文本添加到数组中
    }
    return bicCodes // 返回结果数组
  } catch (error) {
    console.error("Error fetching BIC data:", error)
    return [] // 出错时返回空数组
  }
}

// 组件实现
const DyBicCrawerModal: React.FC<DyBicCrawerModalProps> = ({
  showBicModal,
  handleClose
}) => {
  const [shopList, setShopList] = useState<any[]>([])
  const [shopID, setShopID] = useState<string | number | null>(null)
  const [errMessage, setErrMessage] = useState<string>("")
  const [successMessage, setSuccessMessage] = useState<string>("")
  const [captureCount, setCaptureCount] = useState<number>(500)
  const [bicCount, setBicCount] = useState<number>(0)

  // 抓取进度
  const [captureProgress, setCaptureProgress] = useState<number>(0)
  // 抓取按钮禁用状态
  const [isCaptureBtnDisabled, setIsCaptureBtnDisabled] =
    useState<boolean>(true)
  // 店铺选择下拉框禁用状态
  const [isShopSelectDisabled, setIsShopSelectDisabled] =
    useState<boolean>(false)

  // 获取用户店铺列表函数实现
  const getUserShopListFn = async () => {
    try {
      const data = await getUserShopList()
      const dyShopList = data
        .filter((item: { name: string }) =>
          ["抖音", "测试"].some((keyword) => item.name.indexOf(keyword) !== -1)
        )
        .map((item: { id: string | number | null; name: string }) => ({
          value: item.id,
          label: item.name
        }))
      setShopList(dyShopList)
    } catch (error) {
      setErrMessage("获取店铺列表失败，请稍后再试。")
    }
  }

  // 处理店铺选择更改
  const handleShopChange = async (value: string) => {
    // 设置当前选中的店铺ID
    setShopID(value)
  }

  // 获取店铺可用BIC数量函数实现
  const fetchBicCount = async () => {
    // 使用v3版请求数量，可随时切换v2
    const { data } = await _callApi("getDyShopBicCountV3", shopID)
    setBicCount(data?.available_quantity || data?.count || 0)
  }

  // 处理抓取数据方法
  const fetchDataAndUpload = async () => {
    // 返回数据
    const resData = {
      count: 0,
      success: false
    }
    // 获取bic抓取数据
    const bicList = await fetchBicData()
    resData.count = bicList.length
    if (resData.count === 0) {
      setErrMessage("未抓取到BIC数据，请稍后再试。")
      return resData
    }
    // 上传抓取到的bic数据
    const uploadData = {
      prefix_id: shopID,
      biccode: bicList
    }
    const { err } = await _callApi("uploadDyBicList", uploadData)

    if (err !== "") {
      setErrMessage("上传BIC数据失败，请稍后再试。")
      return resData
    }
    resData.success = true
    return resData
  }

  // 处理开始抓取动作
  const handleStartCapture = async () => {
    // 重置进度
    setCaptureProgress(0)
    // 禁用选择框
    setIsShopSelectDisabled(true)
    // 禁用开始抓取按钮
    setIsCaptureBtnDisabled(true)
    try {
      // 抓取总数
      const _total = Number(captureCount)
      // 当前抓取数量
      let _cur_count = 0
      // 循环比较
      let _loop = true
      // 循环抓取
      while (_loop) {
        const { success, count } = await fetchDataAndUpload()
        _cur_count += count
        if (!success) {
          // 失败则停止抓取
          _loop = false
        } else {
          // 计算抓取进度
          const _progress = (_cur_count / _total) * 100
          setCaptureProgress(_progress)
          if (_cur_count >= _total) {
            // 达到抓取总数则停止抓取
            _loop = false
          }
        }
      }
      // 设置成功信息
      setSuccessMessage(`成功抓取${_cur_count}条BIC数据`)
    } catch (e) {
      console.error("抓取数据并上传时出错", e)
      setErrMessage("抓取BIC出现错误，请联系管理员")
    } finally {
      // 重新获取bic可用数量
      await fetchBicCount()
      // 可用选择框
      setIsShopSelectDisabled(false)
      // 可用开始抓取按钮
      setIsCaptureBtnDisabled(false)
    }
  }

  // 显示状态监控
  useEffect(() => {
    if (showBicModal) {
      getUserShopListFn()
    }
  }, [showBicModal])

  // 店铺id和bic数量更改监控
  useEffect(() => {
    if (shopID) {
      // 抓取按钮可用性控制
      // 已选择店铺，且bicCount数量小于50000时，按钮可用
      setIsCaptureBtnDisabled(!shopID || bicCount >= 50000)
    }
  }, [shopID, bicCount])

  // 添加effect监听shopID变化
  useEffect(() => {
    if (shopID) {
      // 获取bic数量
      fetchBicCount()
    }
  }, [shopID])

  return (
    <Modal
      key="dy-bic-crawer-modal"
      width={950}
      className="shop-base-modal-wrapper dy-bic-crawler-modal-wrapper"
      open={showBicModal}
      footer={false}
      onCancel={handleClose}
      mask={true}
      title="抖音BIC数据抓取"
      getContainer={false}
      maskClosable={false}
      closable={!isCaptureBtnDisabled}>
      <div className="tool-bar-wrapper">
        <div className="tool-block">
          <div>
            <span>大G店铺选择</span>
            <Select
              value={shopID}
              size={"small"}
              style={{ width: 150, marginLeft: 10 }}
              getPopupContainer={(trigger) => {
                return trigger.parentNode
              }}
              placeholder={"请选择店铺"}
              options={shopList}
              disabled={isShopSelectDisabled}
              onChange={handleShopChange}></Select>
          </div>
          <div>BIC可用存量: {bicCount}条</div>
        </div>
        <div className="tool-block">
          <div>
            <span>抓取数量</span>
            <Select
              value={captureCount}
              size={"small"}
              style={{ width: 150, marginLeft: 10 }}
              getPopupContainer={(trigger) => {
                return trigger.parentNode
              }}
              placeholder={"请选择抓取数量"}
              options={[
                { value: 500, label: "500条" },
                { value: 1000, label: "1000条" },
                { value: 2500, label: "2500条" },
                { value: 5000, label: "5000条" },
                { value: 10000, label: "10000条" },
                { value: 15000, label: "15000条" },
                { value: 20000, label: "20000条" }
              ]}
              disabled={isCaptureBtnDisabled}
              onChange={(value) => setCaptureCount(value)}></Select>
          </div>
          <div>
            <Button
              key={"data-capture"}
              size={"small"}
              disabled={isCaptureBtnDisabled} // 根据isCaptureBtnDisabled状态禁用按钮
              onClick={handleStartCapture}>
              数据抓取
            </Button>
          </div>
        </div>
      </div>
      <div>
        <Progress
          percent={captureProgress}
          size={[860, 15]}
          trailColor={"#e3e3e3"}
        />
      </div>
    </Modal>
  )
}

export default DyBicCrawerModal
